<template>
    <div>
        <el-card>
            <div style="margin-bottom: 16px;">
                <el-button type="primary" @click="openAddDialog(null)">
                    <el-icon>
                        <Plus />
                    </el-icon> 添加一级分类
                </el-button>
            </div>

            <!-- 分类表格：树形结构 -->
            <el-table :data="categoryList" :tree-props="{ children: 'children' }" border style="width: 100%"
                row-key="id" v-loading="loading">
                <el-table-column prop="name" min-width="180" label="分类名称" />
                <el-table-column label="分类级别" width="100" align="center">
                    <template #default="scope">
                        <span>{{ getLevelText(getLevel(scope.row)) }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="sort" label="排序号" width="100" />
                <el-table-column align="center" prop="status" label="状态" width="120">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                            {{ scope.row.status === 1 ? '显示' : '隐藏' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="icon" label="图标" width="100">
                    <template #default="scope">
                        <el-image v-if="isImageUrl(scope.row.icon)" :src="scope.row.icon" fit="contain"
                            style="width: 32px;height: 32px;" :preview-src-list="[scope.row.icon]" />
                        <i v-else-if="scope.row.icon" :class="scope.row.icon" style="font-size: 20px;"></i>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="220">
                    <template #default="scope">
                        <!-- 下拉操作菜单 -->
                        <el-dropdown>
                            <el-button size="small">
                                操作
                                <i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <template v-slot:dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item @click="openEditDialog(scope.row)">编辑</el-dropdown-item>
                                    <el-dropdown-item style="color:#f56c6c" @click="handleDelete(scope.row)">
                                        删除
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>

                        <!-- 添加子分类：仅三级以下可加 -->
                        <el-button v-if="getLevel(scope.row) < 3" size="small" @click="openAddDialog(scope.row)"
                            type="danger" style="margin-left: 8px;">
                            + 子分类
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 新增/编辑抽屉：用dialog控制显示 -->
        <el-drawer v-model="dialog" title="分类操作" direction="rtl" size="50%">
            <div class="demo-drawer__content">
                <!-- 表单：加ref="formRef"用于验证，绑定rules -->
                <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                    <el-form-item label="分类名称" prop="name">
                        <el-input v-model="form.name" autocomplete="off" placeholder="请输入分类名称" />
                    </el-form-item>
                    <el-form-item label="排序号" prop="sort"> <!-- 加prop，验证排序号 -->
                        <el-input-number v-model="form.sort" :max="999" :min="1" placeholder="请输入排序号" />
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="显示"
                            inactive-text="隐藏" />
                    </el-form-item>
                    <el-form-item label="图标">
                        <el-input v-model="form.icon" placeholder="请输入图标class（如el-icon-user）或图片URL" />
                        <div style="margin-top: 8px;">
                            <el-image v-if="isImageUrl(form.icon)" :src="form.icon" fit="contain"
                                style="width: 32px;height: 32px; vertical-align: middle;"
                                :preview-src-list="[form.icon]" />
                            <i v-else-if="form.icon" :class="form.icon"
                                style="font-size: 20px; vertical-align: middle;"></i>
                            <span v-else style="color: #ccc;">无预览</span>
                        </div>
                    </el-form-item>
                </el-form>

                <!-- 抽屉底部按钮 -->
                <div class="demo-drawer__footer" style="margin-top: 24px; text-align: right;">
                    <el-button @click="dialog = false">取消</el-button>
                    <el-button type="primary" :loading="loading" @click="doSave" style="margin-left: 8px;">
                        提交
                    </el-button>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script setup>
// 1. 导入必要依赖
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElImage, ElMessageBox } from 'element-plus' // 导入Element组件
import { getCategoryTree, saveCategory, deleteCategory } from '@/api/category.js' // 确保API函数存在
import { Plus, Search } from '@element-plus/icons-vue'
// 2. 定义响应式变量
const categoryList = ref([]) // 分类列表
const loading = ref(false) // 加载状态
const dialog = ref(false) // 抽屉显示控制
const formRef = ref(null) // 表单ref，用于验证
const currentParent = ref(null) // 当前父分类

// 3. 表单数据和验证规则
const form = reactive({
    id: null,
    name: '',
    parentId: 0,
    sort: 1,
    icon: '',
    description: '',
    status: 1
})

const rules = {
    name: [
        { required: true, message: '分类名称不能为空', trigger: 'blur' },
        { max: 50, message: '分类名称不能超过50个字符', trigger: 'blur' }
    ],
    sort: [
        { required: true, message: '排序号不能为空', trigger: 'blur' },
        { type: 'number', message: '排序号必须是数字', trigger: 'blur' }
    ]
}


const openAddDialog = (parent) => {
    dialog.value = true // 打开抽屉
    let maxSort = 0

    // 计算最大排序号，新分类排序+1
    if (parent && parent.children && parent.children.length > 0) {
        maxSort = Math.max(...parent.children.map(child => child.sort || 0))
    } else if (!parent && categoryList.value.length > 0) {
        maxSort = Math.max(...categoryList.value.map(child => child.sort || 0))
    }

    // 重置表单
    form.id = null
    form.name = ''
    form.parentId = parent ? parent.id : 0
    form.sort = maxSort + 1
    form.icon = ''
    form.status = 1
    currentParent.value = parent // ref变量需用.value赋值
}

// 5. 编辑分类：回显数据
const openEditDialog = (row) => {
    console.log('回显数据:', row)
    dialog.value = true
    form.id = row.id
    form.name = row.name
    form.parentId = row.parent?.id || 0
    form.sort = row.sort || 1
    form.icon = row.icon || ''
    form.status = row.status || 1
    currentParent.value = null
}


const doSave = async () => {
    // 表单验证
    formRef.value.validate(async (valid) => {
        if (!valid) return

        // 构造提交数据
        const submitData = {
            id: form.id,
            name: form.name,
            parentId: form.parentId,
            sort: form.sort,
            icon: form.icon,
            status: form.status
        }

        try {
            loading.value = true // 开启加载
            const res = await saveCategory(submitData) // 调用保存API
            if (res.code === 0) {
                ElMessage.success('保存成功！')
                dialog.value = false // 关闭抽屉
                fetchCategoryList() // 重新加载分类列表
            } else {
                ElMessage.error(`保存失败：${res.msg}`)
            }
        } catch (error) {
            ElMessage.error('网络错误，保存失败！')
            console.error('保存错误：', error)
        } finally {
            loading.value = false // 关闭加载
        }
    })
}

// 7. 新增：删除分类（补全原代码缺失的删除逻辑）
const handleDelete = async (row) => {
    if (row.children && row.children.length > 0) {
        ElMessage.error('请先删除子分类！')
        return
    }

    try {
        await ElMessageBox.confirm(
            '确认要删除此分类吗？',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const res = await deleteCategory(row.id)
        if (res.code === 0) {
            ElMessage.success('删除成功！')
            fetchCategoryList() // 刷新分类列表
        } else {
            ElMessage.error(`删除失败：${res.msg}`)
        }
    } catch (error) {
        if (error === 'cancel') return // 用户取消删除
        ElMessage.error('删除失败！')
        console.error('删除错误：', error)
    } finally {
        loading.value = false
    }
}

// 8. 加载分类列表（原代码优化：加错误捕获详情）
const fetchCategoryList = async () => {
    loading.value = true
    try {
        const res = await getCategoryTree()
        if (res.code === 0) {
            // 确保children是数组（防止后端返回null）
            categoryList.value = ensureChildrenArray(res.data)
        } else {
            ElMessage.error(`加载失败：${res.msg}`)
            categoryList.value = [] // 加载失败时清空列表
        }
    } catch (error) {
        ElMessage.error('网络错误，分类加载失败！')
        console.error('加载分类错误：', error)
        categoryList.value = []
    } finally {
        loading.value = false
    }
}

// 9. 工具函数：确保children是数组（防止树形结构报错）
const ensureChildrenArray = (list, parent = null) => {
    return list.map(node => {
        node.children = Array.isArray(node.children) ? node.children : []
        if (node.children.length > 0) {
            ensureChildrenArray(node.children, node)
        }
        node.parent = parent // 给节点加parent属性，用于getLevel计算
        return node
    })
}

// 10. 工具函数：判断是否为图片URL
const isImageUrl = (url) => {
    return typeof url === 'string' && /(https?:\/\/.+\.(png|jpg|jpeg|gif|webp|svg))/i.test(url)
}

// 11. 工具函数：计算分类级别
const getLevel = (row) => {
    let level = 1
    let parent = row.parent
    while (parent) {
        level++
        parent = parent.parent
    }
    return level
}

// 12. 工具函数：级别文本转换
const getLevelText = (level) => {
    const levelMap = { 1: '一级', 2: '二级', 3: '三级' }
    return levelMap[level] || `${level}级`
}

// 13. 组件挂载时加载分类列表
onMounted(() => {
    fetchCategoryList()
})
</script>

<style scoped>
/* 优化抽屉内边距 */
.demo-drawer__content {
    padding: 20px;
}

/* 优化按钮间距 */
.el-button+.el-button {
    margin-left: 8px;
}
</style>